/*
 ** input clear 快速清除输入框内容
 **
 **
 */

(function() {
	'use strict';

	angular
		.module('elife')
		.directive('inputClear', inputClear);

	inputClear.$inject = [];
	/** @ngInject */
	function inputClear() {
		var directive = {
			restrict: 'A',
			link: linkFunc
		};

		return directive;

		function linkFunc(scope, elem, attr) {
			var clearBtn = $('<div class="clear-out hide"></div>');

			clearBtn.insertAfter(elem);

			// 绑定点击事件
			clearBtn.on('click', function() {
				scope.$apply(function() {
					var model = attr.ngModel;
					if (model.indexOf('.') != -1) {
						model = model.split('.');
						scope[model[0]][model[1]] = '';
					} else {
						scope[attr.ngModel] = '';
					}
				});
			});

			// 监听输入值变化
			scope.$watch(attr.ngModel, function(value) {
				// 获取表单禁用状态
				var disabledModel = attr.ngDisabled,
					disabled = false;

				if (disabledModel) {
					if (disabledModel.indexOf('.') != -1) {
						disabledModel = disabledModel.split('.');
						disabled = scope[disabledModel[0]][disabledModel[1]];
					} else {
						disabled = scope[disabledModel];
					}
				}

				// 显示隐藏按钮
				if (value && !disabled) {
					clearBtn.show();
				} else {
					clearBtn.hide();
				}
			});
		}
	}

})();
